package com.wb.mas.ui.auth;

import android.app.Application;
import android.text.TextUtils;

import com.blankj.utilcode.util.SPUtils;
import com.wb.mas.R;
import com.wb.mas.app.Constants;
import com.wb.mas.app.DictInfoTypeKey;
import com.wb.mas.app.SPKeys;
import com.wb.mas.app.UUidUtils;
import com.wb.mas.data.DemoRepository;
import com.wb.mas.entity.DicInfoEntity;
import com.wb.mas.entity.DicInfoResponse;
import com.wb.mas.entity.LocationWrapper;
import com.wb.mas.entity.RootApiBean;
import com.wb.mas.entity.SubmitedAuthResponse;
import com.wb.mas.storage.LocationDao;
import com.wb.mas.utils.response.ResultException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class AuthWorkInfoViewModel extends AuthBaseViewModel {


    private ObservableField<DicInfoEntity> tempSelectedDic;
    private String currentDictType;
    private List<DicInfoEntity> dicInfoList;
    private LocationDao locationDao = new LocationDao();


    public AuthWorkInfoViewModel(@NonNull Application application, DemoRepository model) {
        super(application, model);
        setTitleText(getString(R.string.auth_wi_page_tile));
    }

    public class UiChangeEvent {
        public SingleLiveEvent selectPupEvent = new SingleLiveEvent();
        public SingleLiveEvent showTimeEvent = new SingleLiveEvent();
        public SingleLiveEvent showLocationEvent = new SingleLiveEvent();
    }

    public UiChangeEvent uc = new UiChangeEvent();
    public ObservableField<String> companyName = new ObservableField<>("");
    public ObservableField<DicInfoEntity> workType = new ObservableField<>();
    public ObservableField<DicInfoEntity> jobName = new ObservableField<>();
    public ObservableField<String> workTime = new ObservableField<>("");
    public ObservableField<DicInfoEntity> salary = new ObservableField<>();
    public ObservableField<String> companyPhone = new ObservableField<>("");
    public ObservableField<String> companyNet = new ObservableField<>("");
    public ObservableField<String> companyProvince = new ObservableField<>("");
    public ObservableField<String> companyCity = new ObservableField<>("");
    public ObservableField<String> companyTown = new ObservableField<>("");
    public ObservableField<String> companyRegion = new ObservableField<>("");
    public ObservableField<String> companyDetailAddress = new ObservableField<>("");
    public ObservableField<String> companyPostCode = new ObservableField<>("");


    public BindingCommand workJobClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            tempSelectedDic = jobName;
            getDictsBykey(DictInfoTypeKey.current_position);

        }
    });
    public BindingCommand workTypeCick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            tempSelectedDic = workType;
            getDictsBykey(DictInfoTypeKey.common_professional);

        }
    });
    public BindingCommand workTimeClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            uc.showTimeEvent.setValue("");


        }
    });
    public BindingCommand salaryContainerClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            tempSelectedDic = salary;
            getDictsBykey(DictInfoTypeKey.salary_treatment);

        }
    });
    public BindingCommand companyProvinceClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            ArrayList<String> provinceList = locationDao.getProvince();
            uc.showLocationEvent.setValue(new LocationWrapper(provinceList, companyProvince, getString(R.string.auth_page_please_select_province)));


        }
    });
    public BindingCommand companyCityClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (StringUtils.isEmpty(companyProvince.get())) {
                ToastUtils.showShort(getString(R.string.auth_page_please_select_province));
                return;
            }
            ArrayList<String> cityList = locationDao.getCity(companyProvince.get());
            uc.showLocationEvent.setValue(new LocationWrapper(cityList, companyCity, getString(R.string.auth_page_please_select_city)));

        }
    });
    public BindingCommand companyTownClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            if (StringUtils.isEmpty(companyCity.get())) {
                ToastUtils.showShort(getString(R.string.auth_page_please_select_city));
                return;
            }
            ArrayList<String> townList = locationDao.getTown(companyProvince.get(), companyCity.get());
            uc.showLocationEvent.setValue(new LocationWrapper(townList, companyTown, getString(R.string.auth_page_please_select_town)));
        }
    });
    public BindingCommand companyRegionClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            if (StringUtils.isEmpty(companyTown.get())) {
                ToastUtils.showShort(getString(R.string.auth_page_please_select_town));
                return;
            }
            ArrayList<String> areaList = locationDao.getArea(companyProvince.get(), companyCity.get(), companyTown.get());
            uc.showLocationEvent.setValue(new LocationWrapper(areaList, companyRegion, getString(R.string.auth_page_please_select_area)));

        }
    });
    public BindingCommand onClickNextStep = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            if (TextUtils.isEmpty(companyName.get())) {

                ToastUtils.showShort(getString(R.string.auth_work_please_input_comany_hint));
                return;
            }
            if (workType == null || workType.get() == null || StringUtils.isEmpty(workType.get().dictCode)) {

                ToastUtils.showShort(getString(R.string.auth_work_please_input_comany_type_hint));
                return;
            }
            if (salary == null || salary.get() == null || StringUtils.isEmpty(salary.get().dictCode)) {

                ToastUtils.showShort(getString(R.string.auth_work_please_input_salary_hint));
                return;
            }
            if (jobName == null || jobName.get() == null || StringUtils.isEmpty(jobName.get().dictCode)) {

                ToastUtils.showShort(getString(R.string.auth_work_please_input_job_name_hint));
                return;
            }
            if (TextUtils.isEmpty(workTime.get())) {

                ToastUtils.showShort(getString(R.string.auth_work_please_input_work_time_hint));
                return;
            }
            if (TextUtils.isEmpty(companyPhone.get())) {

                ToastUtils.showShort(getString(R.string.auth_work_please_input_comany_phone_hint));
                return;
            }
            if (TextUtils.isEmpty(companyNet.get())) {

                ToastUtils.showShort(getString(R.string.auth_work_please_input_comany_net_hint));
                return;
            }
            if (TextUtils.isEmpty(companyProvince.get())) {

                ToastUtils.showShort(getString(R.string.auth_work_please_input_comany_province_hint));
                return;
            }
            if (TextUtils.isEmpty(companyCity.get())) {

                ToastUtils.showShort(getString(R.string.auth_work_please_input_comany_city_hint));
                return;
            }
            if (TextUtils.isEmpty(companyTown.get())) {

                ToastUtils.showShort(getString(R.string.auth_work_please_input_comany_town_hint));
                return;
            }
            if (TextUtils.isEmpty(companyRegion.get())) {

                ToastUtils.showShort(getString(R.string.auth_work_please_input_comany_region_hint));
                return;
            }
            if (TextUtils.isEmpty(companyDetailAddress.get())) {

                ToastUtils.showShort(getString(R.string.auth_work_please_input_comany_detail_address_hint));
                return;
            }
            if (TextUtils.isEmpty(companyPostCode.get())
            ) {

                ToastUtils.showShort(getString(R.string.auth_work_please_input_comany_post_code_hint));
                return;
            }

            uploadWorkInfo();


        }
    });

    /**
     * {
     * "workStartTime": "2019-01",   //工作开始时间
     * "userUuid": "20190423953",   //用户uuid
     * "companyCity": "BULELENG",   //市
     * "companyNet": "wee",       //公司网址
     * "companyAddressDesc": "bb",  //详细区域
     * "companyTown": "SERIRIT",   //镇
     * "commonParam": 公参,
     * "authPageCode": "company_code",    //认证步骤标识 通过认证状态获取的
     * "companyRegion": "BUBUNAN",
     * "companyName": "vb",      //公司名称
     * "commonProfessional": "top_management",     //职位标识
     * "companyTel": "2",         //公司电话
     * "companyIndustryCode": "common_professional_25",   //选择的行业类别标识
     * "companyProvince": "BALI",   //省
     * "companyZipcode": "88",    //邮编
     * "channel": "1",          //渠道
     * “isInformationWrong”:1 ,  //如果是资料退回再次上传的 传1  要不是不传
     * "salary": "salary_treatment4"    //收入标识
     * }
     */
    private void uploadWorkInfo() {

        showDialog();
        Map<String, Object> params = new HashMap<>();
        if (SPUtils.getInstance().getBoolean(SPKeys.SP_ISBACK)) {
            params.put("isInformationWrong", "1");

        }
        params.put("authPageCode", Constants.AUTH_PAGE_CODE_COMPANY_CODE);
        params.put("workStartTime", workTime.get());
        params.put("userUuid", UUidUtils.getUUid());
        params.put("companyCity", companyCity.get());
        params.put("companyNet", companyNet.get());
        params.put("companyAddressDesc", companyDetailAddress.get());
        params.put("companyTown", TextUtils.isEmpty(companyTown.get()) ? "" : companyTown.get());
        params.put("companyRegion", TextUtils.isEmpty(companyRegion.get()) ? "" : companyRegion.get());
        params.put("companyName", companyName.get());
        params.put("commonProfessional", jobName.get().dictCode);
        params.put("companyTel", companyPhone.get());
        params.put("companyIndustryCode", workType.get().dictCode);
        params.put("companyProvince", companyProvince.get());
        params.put("companyZipcode", companyPostCode.get());
        params.put("salary", salary.get().dictCode);
        model.saveOrUpdateCustomerInfo(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<RootApiBean>() {
                    @Override
                    public void accept(RootApiBean rootApiBean) throws Exception {

                        dismissDialog();
                        if (rootApiBean != null && rootApiBean.getStatus() == 200) {
                            AuthJumpManager.jumpToNextPage(Constants.AUTH_PAGE_CODE_COMPANY_CODE);
                            finish();

                        } else {
                            if (!TextUtils.isEmpty(rootApiBean.getMessage())) {
                                ToastUtils.showShort(rootApiBean.getMessage());
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();
                        KLog.e("error:" + throwable.getMessage());
                        if (throwable instanceof ResultException) {
                            ToastUtils.showShort(throwable.getMessage());

                        }
                    }
                });

    }


    public void getDictsBykey(final String dictType) {
        Map<String, Object> dictParams = new HashMap<>();
        dictParams.put("dictType", dictType);
        model.getDicInfo(dictParams)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DicInfoResponse>() {
                    @Override
                    public void accept(DicInfoResponse dicInfoResponse) throws Exception {
                        if (dicInfoResponse == null) return;

                        showPopWindow(dictType, dicInfoResponse.getData());


                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        KLog.e("error:" + throwable.getMessage());
                        if (throwable instanceof ResultException) {
                            ToastUtils.showShort(throwable.getMessage());

                        }
                    }
                });

    }

    private void showPopWindow(String dictType, List<DicInfoEntity> data) {
        this.dicInfoList = data;
        this.currentDictType = dictType;
        uc.selectPupEvent.setValue("");

    }


    public String getCurrentDictType() {
        return this.currentDictType;
    }

    public List<DicInfoEntity> getCurrentDictList() {
        return this.dicInfoList;
    }


    public void onItemSelected(String title, int position) {
        if (currentDictType == null || dicInfoList == null || position >= dicInfoList.size() || tempSelectedDic == null)
            return;
        tempSelectedDic.set(dicInfoList.get(position));
    }


    @Override
    public void onCreate() {
        super.onCreate();
        getSubmitedInfo(Constants.AUTH_PAGE_CODE_COMPANY_CODE);
    }


    @Override
    protected void onSubmittedResponse(SubmitedAuthResponse response) {
        super.onSubmittedResponse(response);

        if (response != null && response.getData() != null && response.getData().getCompanyInfo() != null) {
            SubmitedAuthResponse.DataBean.CompanyInfoBean companyInfo = response.getData().getCompanyInfo();

            companyName.set(companyInfo.getCompanyName());
            workType.set(new DicInfoEntity(companyInfo.getCompanyIndustryValue(), companyInfo.getCompanyIndustryCode()));
            jobName.set(new DicInfoEntity(companyInfo.getCommonProfessionalValue(), companyInfo.getCommonProfessional()));//
            workTime.set(companyInfo.getWorkStartTime());
            salary.set(new DicInfoEntity(companyInfo.getSalaryValue(), companyInfo.getSalary()));
            companyPhone.set(companyInfo.getCompanyTel());
            companyNet.set(companyInfo.getCompanyNet());
            companyProvince.set(companyInfo.getCompanyProvince());
            companyCity.set(companyInfo.getCompanyCity());
            companyTown.set(companyInfo.getCompanyTown());
            companyRegion.set(companyInfo.getCompanyRegion());
            companyDetailAddress.set(companyInfo.getCompanyAddressDesc());
            companyPostCode.set(companyInfo.getCompanyZipcode());

        }

    }
}
